import io
import os
import webbrowser

import requests
from PIL import Image

from global_config import get_cur_project, workflows_dir, workflows_img_dir

# 设置请求的URL和头部信息
uploadImg = "https://postimages.org/json/rr"

describe_img = "http://10.31.120.162:7862/v1/tools/describe-image"


def uploadImg(frames_dir):
    isopen = input("是否上传图片, y or n\n")
    if isopen == 'y':
        # 打开帧目录 和 图床网站
        os.startfile(frames_dir)
        webbrowser.open('https://postimages.org/')
        url_list = input('输入urls\n').removesuffix(" ").split(" ")
        return url_list
    return None


def describe_image(image_path, params: dict = {"type": "Photo"}) -> dict:
    with open(image_path, 'rb') as file:
        byte_array = file.read()

        response = requests.post(describe_img,
                                 params=params,
                                 files={
                                     "image": byte_array
                                 },
                                 timeout=30)
        # print(response.json(), response.status_code)

        return response.json()['describe']


def save_mj_img(urlList, nameList):
    workflow_path = f'{workflows_dir}{get_cur_project()}\\'
    image_temp_dir = f'{workflow_path}{workflows_img_dir}\\'
    if not os.path.exists(image_temp_dir):
        os.mkdir(image_temp_dir)

    for i, url in enumerate(urlList):
        filename = nameList[i]
        path = f"{image_temp_dir}{filename}"
        if not os.path.exists(path):
            response = requests.get(url)
            if response.status_code == 200:
                origin_image = Image.open(io.BytesIO(response.content))
                width = int(origin_image.width / 2)
                height = int(origin_image.height / 2)

                image_01 = origin_image.crop((0, 0, width, height))
                image_02 = origin_image.crop((width, height, origin_image.width, origin_image.height))
                image_03 = origin_image.crop((0, height, width, origin_image.height))
                image_04 = origin_image.crop((width, 0, origin_image.width, height))


                path = f"{image_temp_dir}01_{filename}"
                image_01.save(path)
                path = f"{image_temp_dir}02_{filename}"
                image_02.save(path)
                path = f"{image_temp_dir}03_{filename}"
                image_03.save(path)
                path = f"{image_temp_dir}04_{filename}"
                image_04.save(path)
            else:
                print('status_code: ' + str(response.status_code))
        print('image exits')

